package persistance;

import br.com.caelum.vraptor.ioc.ApplicationScoped;
import br.com.caelum.vraptor.ioc.Component;
import br.com.caelum.vraptor.ioc.ComponentFactory;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;

@Component
@ApplicationScoped
public class SessionFactoryCreator implements ComponentFactory<SessionFactory> {
    private SessionFactory factory;

    @PostConstruct
    public void create() {
        try {
            factory = new Configuration().addResource("hibernate.cfg.xml").configure().buildSessionFactory();
        } catch (Throwable ex) {
            throw new ExceptionInInitializerError(ex);
        }
    }

    public SessionFactory getInstance() {
        return factory;
    }

    @PreDestroy
    public void destroy() {
        factory.close();
    }
}